import React, { useState } from 'react';
import { Download, Search, Filter, Grid, List, Play, Pause, X, CheckCircle, AlertCircle, Clock } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import FileIcon from '../components/FileIcon';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

const Downloads = ({ toggleSidebar }) => {
  const [viewMode, setViewMode] = useState('list');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [filterStatus, setFilterStatus] = useState('all');

  // 模拟下载任务数据
  const [downloads, setDownloads] = useState([
    {
      id: 1,
      name: '项目文档.zip',
      type: 'archive',
      size: '25.6 MB',
      downloaded: '15.3 MB',
      progress: 60,
      status: 'downloading', // downloading, paused, completed, error, waiting
      speed: '2.1 MB/s',
      timeLeft: '5秒',
      url: 'https://example.com/project.zip',
      startTime: '2024-01-20 14:30:00'
    },
    {
      id: 2,
      name: '演示视频.mp4',
      type: 'video',
      size: '128.5 MB',
      downloaded: '128.5 MB',
      progress: 100,
      status: 'completed',
      speed: '0 B/s',
      timeLeft: '已完成',
      url: 'https://example.com/video.mp4',
      startTime: '2024-01-20 14:25:00'
    },
    {
      id: 3,
      name: '数据报告.pdf',
      type: 'pdf',
      size: '5.2 MB',
      downloaded: '0 MB',
      progress: 0,
      status: 'paused',
      speed: '0 B/s',
      timeLeft: '已暂停',
      url: 'https://example.com/report.pdf',
      startTime: '2024-01-20 14:20:00'
    },
    {
      id: 4,
      name: '软件安装包.exe',
      type: 'executable',
      size: '45.8 MB',
      downloaded: '12.3 MB',
      progress: 27,
      status: 'error',
      speed: '0 B/s',
      timeLeft: '下载失败',
      url: 'https://example.com/software.exe',
      startTime: '2024-01-20 14:15:00'
    },
    {
      id: 5,
      name: '图片素材.rar',
      type: 'archive',
      size: '89.2 MB',
      downloaded: '0 MB',
      progress: 0,
      status: 'waiting',
      speed: '0 B/s',
      timeLeft: '等待中',
      url: 'https://example.com/images.rar',
      startTime: '2024-01-20 14:35:00'
    }
  ]);

  const filteredDownloads = downloads.filter(download => {
    const matchesSearch = download.name.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || download.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const handleFileSelect = (fileId) => {
    setSelectedFiles(prev => 
      prev.includes(fileId) 
        ? prev.filter(id => id !== fileId)
        : [...prev, fileId]
    );
  };

  const handlePause = (downloadId) => {
    setDownloads(prev => prev.map(download => 
      download.id === downloadId 
        ? { ...download, status: 'paused', speed: '0 B/s', timeLeft: '已暂停' }
        : download
    ));
  };

  const handleResume = (downloadId) => {
    setDownloads(prev => prev.map(download => 
      download.id === downloadId 
        ? { ...download, status: 'downloading', speed: '1.8 MB/s', timeLeft: '计算中...' }
        : download
    ));
  };

  const handleCancel = (downloadId) => {
    setDownloads(prev => prev.filter(download => download.id !== downloadId));
    setSelectedFiles(prev => prev.filter(id => id !== downloadId));
  };

  const handleRetry = (downloadId) => {
    setDownloads(prev => prev.map(download => 
      download.id === downloadId 
        ? { ...download, status: 'downloading', speed: '1.5 MB/s', timeLeft: '计算中...' }
        : download
    ));
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'downloading':
        return <Download className="w-5 h-5 text-blue-600 animate-pulse" />;
      case 'paused':
        return <Pause className="w-5 h-5 text-yellow-600" />;
      case 'completed':
        return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'error':
        return <AlertCircle className="w-5 h-5 text-red-600" />;
      case 'waiting':
        return <Clock className="w-5 h-5 text-material-grey-500" />;
      default:
        return <Download className="w-5 h-5 text-material-grey-500" />;
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'downloading':
        return 'text-blue-600';
      case 'paused':
        return 'text-yellow-600';
      case 'completed':
        return 'text-green-600';
      case 'error':
        return 'text-red-600';
      case 'waiting':
        return 'text-material-grey-500';
      default:
        return 'text-material-grey-600';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'downloading':
        return '下载中';
      case 'paused':
        return '已暂停';
      case 'completed':
        return '已完成';
      case 'error':
        return '下载失败';
      case 'waiting':
        return '等待中';
      default:
        return '未知状态';
    }
  };

  const downloadingCount = downloads.filter(d => d.status === 'downloading').length;
  const completedCount = downloads.filter(d => d.status === 'completed').length;
  const errorCount = downloads.filter(d => d.status === 'error').length;
  const pausedCount = downloads.filter(d => d.status === 'paused').length;

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <Download className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    下载管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理您的下载任务和已下载文件
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索下载文件..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="downloading">下载中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="paused">已暂停</SelectItem>
                  <SelectItem value="error">失败</SelectItem>
                  <SelectItem value="waiting">等待中</SelectItem>
                </SelectContent>
              </Select>

              <div className="flex items-center bg-material-grey-100 rounded-lg p-1">
                <Button
                  variant={viewMode === 'grid' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('grid')}
                  className="px-3"
                >
                  <Grid className="w-4 h-4" />
                </Button>
                <Button
                  variant={viewMode === 'list' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('list')}
                  className="px-3"
                >
                  <List className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">下载中</p>
                  <p className="text-2xl font-bold text-blue-600">{downloadingCount}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Download className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已完成</p>
                  <p className="text-2xl font-bold text-green-600">{completedCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已暂停</p>
                  <p className="text-2xl font-bold text-yellow-600">{pausedCount}</p>
                </div>
                <div className="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                  <Pause className="w-6 h-6 text-yellow-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">失败</p>
                  <p className="text-2xl font-bold text-red-600">{errorCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <AlertCircle className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 下载列表 */}
        <div className="mt-6">
          <div className="bg-white rounded-lg shadow-material-1 overflow-hidden">
            {/* 表头 */}
            <div className="bg-material-grey-50 border-b border-material-grey-200 px-4 py-3">
              <div className="flex items-center">
                <div className="w-8"></div>
                <div className="flex-1 grid grid-cols-12 gap-4 text-sm font-medium text-material-grey-700">
                  <div className="col-span-4">文件名</div>
                  <div className="col-span-2">大小/进度</div>
                  <div className="col-span-2">状态</div>
                  <div className="col-span-2">速度/剩余时间</div>
                  <div className="col-span-2">操作</div>
                </div>
              </div>
            </div>

            {/* 下载列表 */}
            <div className="divide-y divide-material-grey-200">
              {filteredDownloads.map((download) => (
                <div
                  key={download.id}
                  className={`file-list-item ${
                    selectedFiles.includes(download.id) ? 'bg-primary/5' : ''
                  }`}
                  onClick={() => handleFileSelect(download.id)}
                >
                  <div className="w-8 flex-shrink-0">
                    <input
                      type="checkbox"
                      checked={selectedFiles.includes(download.id)}
                      onChange={(e) => {
                        e.stopPropagation();
                        handleFileSelect(download.id);
                      }}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </div>

                  <div className="flex-1 grid grid-cols-12 gap-4 items-center">
                    <div className="col-span-4 flex items-center space-x-3">
                      <FileIcon type={download.type} size="small" />
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-material-grey-800 truncate">
                          {download.name}
                        </p>
                        <p className="text-xs text-material-grey-500 truncate">
                          {download.url}
                        </p>
                      </div>
                    </div>

                    <div className="col-span-2">
                      <div className="space-y-1">
                        <div className="flex justify-between text-xs">
                          <span className="text-material-grey-600">{download.downloaded}</span>
                          <span className="text-material-grey-500">{download.size}</span>
                        </div>
                        {download.status !== 'completed' && download.status !== 'waiting' && (
                          <Progress value={download.progress} className="h-1" />
                        )}
                      </div>
                    </div>

                    <div className="col-span-2 flex items-center space-x-2">
                      {getStatusIcon(download.status)}
                      <span className={`text-sm ${getStatusColor(download.status)}`}>
                        {getStatusText(download.status)}
                      </span>
                    </div>

                    <div className="col-span-2">
                      <div className="text-sm text-material-grey-600">
                        <div>{download.speed}</div>
                        <div className="text-xs text-material-grey-500">{download.timeLeft}</div>
                      </div>
                    </div>

                    <div className="col-span-2 flex justify-end space-x-2">
                      {download.status === 'downloading' && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            handlePause(download.id);
                          }}
                          className="text-yellow-600 hover:text-yellow-700"
                        >
                          <Pause className="w-4 h-4" />
                        </Button>
                      )}
                      
                      {(download.status === 'paused' || download.status === 'error') && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            download.status === 'paused' ? handleResume(download.id) : handleRetry(download.id);
                          }}
                          className="text-green-600 hover:text-green-700"
                        >
                          <Play className="w-4 h-4" />
                        </Button>
                      )}
                      
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleCancel(download.id);
                        }}
                        className="text-red-600 hover:text-red-700"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* 空状态 */}
        {filteredDownloads.length === 0 && (
          <div className="text-center py-12">
            <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
              <Download className="w-8 h-8 text-material-grey-500" />
            </div>
            <h3 className="text-lg font-medium text-material-grey-700 mb-2">
              {searchQuery ? '未找到匹配的下载任务' : '暂无下载任务'}
            </h3>
            <p className="text-material-grey-500">
              {searchQuery ? '尝试使用不同的关键词搜索' : '开始下载文件后，任务将显示在这里'}
            </p>
          </div>
        )}
      </div>
    </>
  );
};

export default Downloads;
